package com.c.ctgproject.ui.collect.check

import android.content.Intent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.c.ctgproject.adapter.guang.CreatePassCheckAdapter
import com.c.ctgproject.base.BaseActivityV2
import com.c.ctgproject.databinding.ActivityCreatePassCheckBinding
import com.c.ctgproject.entity.guang.AllDepartEntity
import com.c.ctgproject.entity.guang.CheckCreateAttrsBean
import com.c.ctgproject.entity.guang.CheckDetailEntity
import com.c.ctgproject.entity.guang.CheckPassDetailBean
import com.c.ctgproject.enum.DictionaryMenuEnum
import com.c.ctgproject.http.ApiMethods
import com.c.ctgproject.http.MyObserverHandlerLoading
import com.c.ctgproject.ui.collect.DictionaryMenuActivity
import com.c.ctgproject.ui.collect.MaterialOutAboutOrderActivity
import com.c.ctgproject.utils.*
import com.lwkandroid.imagepicker.ImagePicker
import com.lwkandroid.imagepicker.data.ImageBean
import com.lwkandroid.widget.ninegridview.NineGridBean
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult
import java.io.File

/**
 *作者:LiBW
 *创建日期: 2021/10/12
 *描述: 新建放行审批 发起审批 页面
 */
class CreatePassCheckActivity : BaseActivityV2() {
    private val mBinding by lazy { ActivityCreatePassCheckBinding.inflate(layoutInflater) }
    override fun getLayout() = mBinding.root
    private val mList = ArrayList<CheckPassDetailBean>()
    private val mAdapter by lazy { CreatePassCheckAdapter(this, mList, adapterCallback) }
    private val imageShowList = ArrayList<String>()
    private val imageResultCode = 1000

    //部门名称
    private var department = ""


    //携物单位
    private var carryingEnterprise = ""


    //审核人员
    private var auditPersonName = ""
    private var auditPersonId = -1

    //关联出库单号
    private var outOrderId = -1


    //旧数据 有就是继续提交
    private val stripId by lazy { intent.getIntExtra(MyConstants.ID, -1) }

    //是否为草稿 如果有旧数据 而且不是草稿 那么就是驳回的重新申请
    private val isDraft by lazy { intent.getBooleanExtra(MyConstants.Draft, false) }

    //已审批的单子被拒绝可以修改后重新提交
    private val isChange by lazy { intent.getBooleanExtra(MyConstants.CHANGE, false) }

    //未审批的单子 继续编辑后提交
    private val isUpdate by lazy { intent.getBooleanExtra(MyConstants.UPDATE, false) }

    override fun event() {
        ApiMethods.apiSubscribe(ApiMethods.urmRetrofit.getAllDepartment(), MyObserverHandlerLoading(this, loading, zeroIsSuccess = true) {
            MyLog.d("查询所有部门:$it")
            val data = getGson().fromJson(it, AllDepartEntity::class.java).data
            data?.let { list ->
                MyLog.d("查询所有部门1")
                if (list.isNotEmpty()) {
                    val name = list[0].name.handlerNull()
                    department = name
                    mBinding.mDepartment.text = name
                }
            }
        })

        mBinding.mPhotoNGV.init(this, imageShowList, 9, imageResultCode)
        mList.add(CheckPassDetailBean())
        mBinding.mAddRV.adapter = mAdapter
        mBinding.mAddRV.layoutManager = LinearLayoutManager(this)

        //是草稿或者驳回的重新提交
        if (stripId != -1) {
            handlerOldData()
            mBinding.mTitleBar.setTitle("编辑放行申请")
            mBinding.mMineTV.visibility = View.GONE
            if (isDraft) {
                //支持删除草稿
                mBinding.mDeleteDraftTV.visibility = View.VISIBLE
            }
            if (isChange || isUpdate) {
                //被拒绝的单子 和待审批的单子 修改申请重新提交 不能再存为草稿了
                mBinding.mDraftBTN.visibility = View.GONE
            }

        }
    }

    override fun click() {
        //我的
        mBinding.mMineTV.setOnClickListener {
            startActivity<MyFlowCheckActivity>()
        }
        //删除草稿
        mBinding.mDeleteDraftTV.setOnClickListener {
            ApiMethods.apiSubscribe(ApiMethods.retrofit.deleteMyDraft(stripId), MyObserverHandlerLoading(this, loading) {
                MyLog.d("回调:$it")
                showToast("删除成功")
                finish()
            })

        }
        //选择关联出库单
        mBinding.mAboutOrderLL.setOnClickListener {
            startActivityForResult<MaterialOutAboutOrderActivity>(1001)
        }

        //选择审批人
        mBinding.mCheckerLL.setOnClickListener {
            DictionaryMenuActivity.jumpToDictionary(this@CreatePassCheckActivity, DictionaryMenuEnum.CHECK_USER.menuCode, true, arrayListOf(auditPersonName), resultCode = 104, partFrom = 4, canInput = false)
        }


        //选择携物单位
        mBinding.carryingEnterpriseLL.setOnClickListener {
            DictionaryMenuActivity.jumpToDictionary(this@CreatePassCheckActivity, DictionaryMenuEnum.CUSTOMER.menuCode, true, arrayListOf(carryingEnterprise), resultCode = 103)
        }
        mBinding.carPlate.handlerToUpperCase()
        //添加明细
        mBinding.mAddRL.setOnClickListener {
            mList.add(CheckPassDetailBean())
            mAdapter.notifyItemInserted(mList.size)
        }
        //存草稿
        mBinding.mDraftBTN.setOnClickListener {
            checkData(0)
        }
        //提交按钮
        mBinding.mConfirmBTN.setOnClickListener {
            checkData(1)
        }
    }

    //数据提交
    private fun submitToHttp(submit: Int, imageList: ArrayList<String>) {
        MyLog.d("图片有么:$imageList")
        val map = HashMap<String, Any>()
        //新建状态，默认为草稿状态 【0-草稿 1-待审核】

        if (!isDraft) {
            //不是草稿就告诉他我要提交还是草稿
            map["status"] = submit
        }

        if (stripId != -1) {
            map["stripId"] = stripId
        }
        map["department"] = department
        map["auditPersonName"] = auditPersonName
        map["auditPersonId"] = auditPersonId
        map["carryingEnterprise"] = carryingEnterprise
        map["carrier"] = mBinding.carrier.text.handlerNull()
        map["plate"] = mBinding.carPlate.text.handlerNull()
        //关联出库单ID
        if (outOrderId != -1) {
            map["outOrderId"] = outOrderId
        }
        map["releaseItems"] = mList
        val attrList = ArrayList<CheckCreateAttrsBean>()
        imageList.forEach {
            val b = CheckCreateAttrsBean()
            b.attUrl = it
            attrList.add(b)
        }
        map["attachmentList"] = attrList
        //新建状态，默认为草稿状态 【0-草稿 1-待审核】
        if (isDraft && submit == 0) {
            //草稿单重新提交草稿
            ApiMethods.apiSubscribe(ApiMethods.retrofit.releaseStripAddDarftAgain(handlerBody(map)), MyObserverHandlerLoading(this, loading) {
                MyLog.d("回调回调:$it")
                handlerHttpResult(it) {
                    showToast("提交成功")
                    finish()
                }
            })
        } else {
            if (stripId != -1) {
                if (isUpdate) {
                    //待审批的放行条可以再编辑
                    ApiMethods.apiSubscribe(ApiMethods.retrofit.releaseStringSecondUpdate(handlerBody(map)), MyObserverHandlerLoading(this, loading) {
                        MyLog.d("回调:$it")
                        showToast("提交成功")
                        finish()
                    })
                } else {
                    //如果有旧ID说明是草稿单二次提交或者驳回单子二次提交
                    ApiMethods.apiSubscribe(ApiMethods.retrofit.releaseStringSecond(handlerBody(map)), MyObserverHandlerLoading(this, loading) {
                        MyLog.d("回调回调:$it")
                        showToast("提交成功")
                        finish()
                    })
                }
            } else {
                if (submit == 0) {
                    //草稿新搞了个接口...
                    ApiMethods.apiSubscribe(ApiMethods.retrofit.releaseStripAddDraft(handlerBody(map)), MyObserverHandlerLoading(this, loading) {
                        MyLog.d("回调:$it")
                        showToast("提交成功")
                        finish()
                    })

                } else {
                    //新单子提交审批或者提交草稿
                    ApiMethods.apiSubscribe(ApiMethods.retrofit.releaseStripAdd(handlerBody(map)), MyObserverHandlerLoading(this, loading) {
                        MyLog.d("回调回调:$it")
                        showToast("提交成功")
                        finish()
                    })
                }
            }
        }
    }

    //检验数据 0为草稿 1为提交
    private fun checkData(submit: Int) {
        if (submit == 1) {
            mList.forEach {
                if (it.name.handlerNull().isEmpty() ||
                    it.type.handlerNull().isEmpty() ||
                    it.unit.handlerNull().isEmpty() ||
                    it.count.handlerNull().isEmpty()
                ) {
                    showToast("请填写完整的物品明细")
                    mBinding.mAddRV.myShake()
                    return
                }
            }
        }
        when {
            submit == 1 && department.isEmpty() -> {
                showToast("部门不能为空")
            }
            submit == 1 && auditPersonName.isEmpty() -> {
                showToast("请选择审批人")
                mBinding.mCheckerLL.myShake()
            }
            submit == 1 && carryingEnterprise.isEmpty() -> {
                showToast("请选择携物单位")
                mBinding.carryingEnterpriseLL.myShake()
            }
            submit == 1 && mBinding.carrier.text.handlerNull().isEmpty() -> {
                showToast("请填写携物人")
                mBinding.mCarrierLL.myShake()
            }
            submit == 1 && mBinding.carPlate.text.handlerNull().isEmpty() -> {
                showToast("请填写车牌号")
                mBinding.mPlateLL.myShake()
            }
            submit == 1 && imageShowList.isEmpty() -> {
                showToast("请选择物品/磅单照片")
                mBinding.mImageLL.myShake()
            }
            else -> {
                //所有本地文件的图片
                val filePathList = ArrayList<String>()
                imageShowList.forEach {
                    if (!it.startsWith("http")) {
                        filePathList.add(it)
                    }
                }
                if (filePathList.isNotEmpty()) {
                    val fileList = ArrayList<File>()
                    var index = 0
                    filePathList.forEach {
                        index++
                        val file = File(it)
                        //图片压缩
//                            val newFile: File = CompressHelper.getDefault(this).compressToFile(file)
//                        val newFile = ImageUtil.imageWaterMark(this, file, index)
                        val newFile: File = WaterRemark.handlerWaterRemark2File(this, file, index.toString())
                        fileList.add(newFile)
                    }
                    upDataFile(fileList) {
                        val dataList = ArrayList<String>()
                        it?.forEach { b ->
                            dataList.add(b.fileUrl.handlerNull())
                        }
                        MyLog.d("有新的文件")
                        //旧的也给他
                        imageShowList.forEach { bean ->
                            if (bean.startsWith("http")) {
                                dataList.add(bean)
                            }
                        }
                        submitToHttp(submit, dataList)
                    }
                } else {
                    //没有新文件 但是有旧的url
                    submitToHttp(submit, imageShowList)
                }
            }
        }
    }

    //处理旧数据
    private fun handlerOldData() {
        ApiMethods.apiSubscribe(ApiMethods.retrofit.releaseStrip(stripId), MyObserverHandlerLoading(this, loading) {
            MyLog.d("放行条详情回调回调回调:$it")
            val data = getGson().fromJson(it, CheckDetailEntity::class.java).data
            //获取attr图片
            val imageUrls = ArrayList<String>()
            data?.attachments?.forEach { bean ->
                imageUrls.add(bean.attUrl.handlerNull())
            }
            if (imageUrls.isNotEmpty()) {
                val resultList: MutableList<NineGridBean> = ArrayList()
                imageUrls.forEach { bean ->
                    val nineGirdData = NineGridBean(bean)
                    imageShowList.add(bean)
                    resultList.add(nineGirdData)
                }
                mBinding.mPhotoNGV.addDataList(resultList)
            }

            //放行条明细
            mList.clear()
            data?.releaseItems?.forEach { bean ->
                val b = CheckPassDetailBean()
                b.count = bean.count
                b.name = bean.name.handlerNull()
                b.name2 = bean.name2.handlerNull()
                b.remark = bean.remark.handlerNull()
                b.type = bean.type.handlerNull()
                b.unit = bean.unit.handlerNull()
                mList.add(b)
            }
            mAdapter.notifyDataSetChanged()

            data?.let { bean ->
                mBinding.mDepartment.text = bean.department.handlerNull()
                department = bean.department.handlerNull()
                mBinding.carryingEnterpriseTV.text = bean.carryingEnterprise.handlerNull()
                carryingEnterprise = bean.carryingEnterprise.handlerNull()
                mBinding.carrier.textSet(bean.carrier.handlerNull())
                mBinding.carPlate.textSet(bean.plate.handlerNull())
                //审核人员
                bean.auditPersonId?.let { id ->
                    auditPersonName = bean.auditPersonName.handlerNull()
                    auditPersonId = id
                    mBinding.mCheckerTV.text = auditPersonName
                }
            }
            //关联出库单
            data?.outOrderInfo?.bizNo?.let { no ->
                mBinding.mAboutOrderTV.text = no
            }

            handlerCount()
        })
    }

    private var currentPosition = 0


    //物品明细列表回调
    private val adapterCallback = object : CreatePassCheckAdapter.CreatePassCheckAdapterListener {
        override fun onPartNameNeedSelect(position: Int) {
            currentPosition = position
            DictionaryMenuActivity.jumpToDictionary(this@CreatePassCheckActivity, DictionaryMenuEnum.PART_NAME.menuCode, true, arrayListOf(mList[position].name), resultCode = 100)
        }

        override fun onPartTypeNeedSelect(position: Int) {
            currentPosition = position
            DictionaryMenuActivity.jumpToDictionary(this@CreatePassCheckActivity, DictionaryMenuEnum.PART_TYPE.menuCode, true, arrayListOf(mList[position].type), resultCode = 101)
        }

        override fun onPartUnitNeedSelect(position: Int) {
            currentPosition = position
            DictionaryMenuActivity.jumpToDictionary(this@CreatePassCheckActivity, DictionaryMenuEnum.UNIT.menuCode, true, arrayListOf(mList[position].unit), resultCode = 102)
        }

        override fun onCountChange() {
            handlerCount()
        }
    }

    private fun handlerCount() {
        var count = 0
        mList.forEach {
            it.count?.let { c ->
                count += c
            }
        }
        "总数量: $count".also { mBinding.mAllCountTV.text = it }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        data?.let { result ->
            when (requestCode) {
                100 -> {
                    //字典回调 配件名称
                    val name = result.getStringExtra(MyConstants.NAME)
//                val abbreviation=result.getStringExtra(MyConstants.ABBREVIATION)
                    mList[currentPosition].name = name.handlerNull()
                    mAdapter.notifyItemChanged(currentPosition)
                }
                101 -> {
                    //字典回调 配件Type
                    val name = result.getStringExtra(MyConstants.NAME)
//                val abbreviation=result.getStringExtra(MyConstants.ABBREVIATION)
                    mList[currentPosition].type = name.handlerNull()
                    mAdapter.notifyItemChanged(currentPosition)
                }
                102 -> {
                    //字典回调 配件Type
                    val name = result.getStringExtra(MyConstants.NAME)
//                val abbreviation=result.getStringExtra(MyConstants.ABBREVIATION)
                    mList[currentPosition].unit = name.handlerNull()
                    mAdapter.notifyItemChanged(currentPosition)
                }
                103 -> {
                    //字典回调 携物单位
                    val name = result.getStringExtra(MyConstants.NAME).handlerNull()
                    mBinding.carryingEnterpriseTV.text = name
                    carryingEnterprise = name
//                val abbreviation=result.getStringExtra(MyConstants.ABBREVIATION)
                }
                104 -> {
                    //审批人员回调
                    val name = result.getStringExtra(MyConstants.NAME).handlerNull()
                    val abbreviation = result.getStringExtra(MyConstants.ABBREVIATION).handlerNull()
                    auditPersonName = name
                    auditPersonId = abbreviation.toInt()
                    mBinding.mCheckerTV.text = name
                }

                1000 -> {
                    //图片回调
                    val list: List<ImageBean>? = data.getParcelableArrayListExtra(ImagePicker.INTENT_RESULT_DATA)
                    val resultList: MutableList<NineGridBean> = ArrayList()
                    list?.forEach { imageBean ->
                        val nineGirdData = NineGridBean(imageBean.imagePath)
                        imageShowList.add(imageBean.imagePath)
                        resultList.add(nineGirdData)
                    }
                    mBinding.mPhotoNGV.addDataList(resultList)
                }
                1001 -> {
                    //关联出库单
                    val id = data.getIntExtra(MyConstants.ORDER_ID, -1)
                    val no = data.getStringExtra(MyConstants.ORDER_NO).handlerNull()
                    outOrderId = id
                    mBinding.mAboutOrderTV.text = no

                }
            }
        }
    }
}